//
//  JMPublicAlertView.m
//  NewiOSProject
//
//  Created by MAC on 2023/9/1.
//  Copyright © 2023 范智渊. All rights reserved.
//

#import "JMPublicAlertView.h"
@interface JMPublicAlertView()
//底部背景试图
@property(nonatomic)UIButton *coverBtn;
//关闭按钮
@property(nonatomic)JMPublicAlertViewPosition position;
@property (nonatomic, strong)NSTimer *timer;//当前滑动的值
@property (nonatomic, assign) NSTimeInterval time;

@end
@implementation JMPublicAlertView
-(instancetype)initWithFrame:(CGRect)frame andTitle:(NSString *)title subTitle:(NSString *)subTitle BottomBtns:(NSArray *)btnTitles Position:(JMPublicAlertViewPosition)position btnDirection:(JMPublicAlertViewButtonDirection)direction
{
    if(self = [super initWithFrame:frame]){
        _position = position;
        self.layer.cornerRadius = ScaleW(8);
        self.layer.masksToBounds = NO;
        self.backgroundColor = WhiteColor();
        
        //底板
        self.coverBtn = [[UIButton alloc]initWithFrame:(CGRectMake(0, 0, kAppW(), kAppH()))];
        self.coverBtn.backgroundColor = HexAlpha_Str_COLOR(@"#000000", 0.3);
        
        self.topImgV = [[UIImageView alloc]initWithFrame:(CGRectMake(0, 0, frame.size.width, self.width*(38.0/68.0)))];
//        self.topImgV.image = ImageNamed(@"alert_bg_coin");
        [self addSubview:self.topImgV];
        if ([subTitle containsString:@"¿Quiere aumentar"]) {
            self.topImgV.width = 75;
            self.topImgV.height = 75;
            self.topImgV.top = 24;
            [self.topImgV setImage:ImageNamed(@"home_fico")];
            self.topImgV.centerX = self.width/2;
        }
        
        self.titleLab = [JMControl createLabelWithFrame:(CGRectMake(0, 24, frame.size.width,FontH(16))) Font:fontWithWeight(15, UIFontWeightMedium) Text:title color:Text_COLOR_LEVEL1()];
        self.titleLab.textAlignment = 1;
        [self addSubview:self.titleLab];
        self.titleLab.height = CalculateLabelHeightWithLab(self.titleLab);
        self.titleLab.top = 24;
        
        
        
        self.subtitleLab = [[UILabel alloc]initWithFrame:(CGRectMake(24, self.titleLab.bottom, self.width-48, CalculateLabelHeight(self.width-48, Font(15), subTitle)))];
        
        self.subtitleLab.text = subTitle;
        self.subtitleLab.font = Font(15);
        self.subtitleLab.numberOfLines = 0;
        self.subtitleLab.textColor = Text_COLOR_LEVEL1();
        self.subtitleLab.top = self.titleLab.bottom+10;
        [self addSubview:self.subtitleLab];
        if ([subTitle containsString:@"90%"]) {
            [JMControl changeTextColorWithLabel:self.subtitleLab changeStr:@"90%" color:Hex_Str_COLOR(@"#3C57F8")];
        }
        if(self.subtitleLab.height<=FontH(14)){
            self.subtitleLab.textAlignment  =1;
        }
        if (title.length==0) {
            self.subtitleLab.top = 24;
        }
        if(btnTitles.count==1){
            
            CGFloat top;
            if(position==JMPublicAlertViewPositionBottom){
                self.top = kAppH()-self.height+ScaleW(30);
                top =  (self.height-76-kSafeAreaBottomHeight());
                [self.coverBtn addTarget:self action:@selector(dismiss) forControlEvents:(UIControlEventTouchUpInside)];
            }else{
                top = self.height - 76;
                self.centerX = kAppW()/2;
                self.centerY = kAppH()/2;
            }
            self.firstBtn = [JMControl createLoadingButtonWithFrame:(CGRectMake(20, top, self.width-40, 52)) Target:self Action:@selector(botBtnAction:) Title:btnTitles[0] titlColor:Hex_Str_COLOR(@"#FEFFCC") font:Font(14) tag:0 backgroundColor:Button_ENABLE_BG_COLOR()];
            [self addSubview:self.firstBtn];
            self.firstBtn.cornerRadius = 26;
            [self.coverBtn addTarget:self action:@selector(dismiss) forControlEvents:(UIControlEventTouchUpInside)];
        }else{
            CGFloat top;
            if(position==JMPublicAlertViewPositionBottom){
                top =  (self.height-ScaleW(30)-kSafeAreaBottomHeight()-60-46);
                [self.coverBtn addTarget:self action:@selector(dismiss) forControlEvents:(UIControlEventTouchUpInside)];

            }else{
                top = self.height - 76;
                self.centerY = kAppH()/2;
                self.centerX = kAppW()/2;
            }
            if(direction==JMPublicAlertViewButtonDirectionHor){
                self.firstBtn = [JMControl createLoadingButtonWithFrame:(CGRectMake(20, top, (self.width-50)/2, 52)) Target:self Action:@selector(botBtnAction:) Title:btnTitles[0] titlColor:Hex_Str_COLOR(@"#0F1511") font:Font(14) tag:0 backgroundColor:UIColor.whiteColor];
                [self addSubview:self.firstBtn];
                self.firstBtn.layer.borderColor = Hex_Str_COLOR(@"#DFDFDF").CGColor;
                self.firstBtn.layer.borderWidth = 1;
                self.firstBtn.cornerRadius = self.firstBtn.height/2;

                self.secondBtn = [JMControl createLoadingButtonWithFrame:(CGRectMake(self.firstBtn.right+10, top, (self.width-50)/2, 52)) Target:self Action:@selector(botBtnAction:) Title:btnTitles[1]
                                                            titlColor:Hex_Str_COLOR(@"#FEFFCC") font:Font(14) tag:1 backgroundColor:Button_ENABLE_BG_COLOR()];
                [self addSubview:self.secondBtn];
                self.secondBtn.cornerRadius = self.secondBtn.height/2;
            }else{
               
                
                self.secondBtn = [JMControl createLoadingButtonWithFrame:(CGRectMake(20, self.height-76, self.width-40, 52)) Target:self Action:@selector(botBtnAction:) Title:btnTitles[1] titlColor:Hex_Str_COLOR(@"#0F1511") font:Font(14) tag:1 backgroundColor:UIColor.whiteColor];
                self.secondBtn.unableableBgColor = UIColor.clearColor;
                self.secondBtn.enableTextColor = mainSchemeColor();
                [self addSubview:self.secondBtn];
                self.secondBtn.layer.borderColor = Hex_Str_COLOR(@"#3C57F8").CGColor;
                self.secondBtn.layer.borderWidth = 1;
                self.secondBtn.cornerRadius = self.secondBtn.height/2;
                
                self.firstBtn = [JMControl createLoadingButtonWithFrame:(CGRectMake(20, self.secondBtn.top-20-self.secondBtn.height, self.width-40, self.secondBtn.height)) Target:self Action:@selector(botBtnAction:) Title:btnTitles[0] titlColor:Hex_Str_COLOR(@"#FEFFCC") font:Font(14) tag:0 backgroundColor:Button_ENABLE_BG_COLOR()];
                [self addSubview:self.firstBtn];
                self.firstBtn.cornerRadius = self.secondBtn.height/2;;
            }
        }
    }
    return self;
}
- (void)startTimer {
    // 如果只有一张，直接放回，不需要开启定时器
//    if (_images.count <= 1) return;
    self.time = 5;
    // 如果定时器已经开启，则先停止再开启
    if (self.timer) [self stopTimer];
    self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(setBtn) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self.timer fireDate];
}
// 关闭定时器
- (void)stopTimer {
    [self.timer invalidate];
    self.timer = nil;
}
-(void)setBtn{
    self.time -=1;
    if (self.time>0) {
            [self.firstBtn setTitle:[NSString stringWithFormat:@"%lds",@(self.time).intValue] forState:(UIControlStateNormal)];
    }else{
        [self dismiss];
    }
    
}
+(instancetype)showAlertWithFrame:(CGRect)frame Title:(NSString *)title subTitle:(NSString *)subTitle BottomBtns:(NSArray *)btnTitles Position:(JMPublicAlertViewPosition)position btnDirection:(JMPublicAlertViewButtonDirection)direction
           btnActionBlock:(void(^)(NSInteger btnTag))actionBlock
{
    JMPublicAlertView*view = [[self alloc]initWithFrame:frame andTitle:title subTitle:subTitle BottomBtns:btnTitles Position:position btnDirection:direction];
    [view.secondBtn tapAction:^(UIView *sender) {
        [view dismiss];
        actionBlock(sender.tag);
    }];
    [view.firstBtn tapAction:^(UIView *sender) {
        [view dismiss];
        actionBlock(sender.tag);
    }];
    [view show];
    return view;
}
-(void)setButtonNeedLoading:(BOOL)buttonNeedLoading{
    _buttonNeedLoading = buttonNeedLoading;
    
}
-(void)botBtnAction:(JMLoadingButton *)sender{
    if([self.delegate respondsToSelector:@selector(didClickBtnAtIndex:withButton:)]){
        [self.delegate didClickBtnAtIndex:sender.tag withButton:sender];
        [sender startLoading];

    }
}
-(NSArray<UIButton *> *)buttons{
    NSMutableArray *btns = @[].mutableCopy;
    for (JMLoadingButton*btn in self.subviews) {
        if([btn isKindOfClass:JMLoadingButton.class]){
            [btns addObject:btn];
        }
    }
    return btns;
}
//MARK: -action

-(UIButton *)closeBtn{
    if(!_closeBtn){
        _closeBtn = [JMControl createButtonWithFrame:(CGRectMake(0, 0, 48, 48)) buttonType:(UIButtonTypeSystem) buttonImageWithName:@"ICON／che hui" Target:self Action:@selector(closeBtnClick)];
        _closeBtn.top = self.top-78;
        _closeBtn.right = kAppW()-24;
    }
    return _closeBtn;
}
-(void)closeBtnClick{
    if([self.delegate respondsToSelector:@selector(closeBtnClick)]){
        [self.delegate closeBtnDidClick];
    }
    [self dismiss];
}
-(void)show{
    [self.coverBtn addSubview:self];
    [self.coverBtn addSubview:self.closeBtn];
    if ([self.firstBtn.titleLabel.text isEqualToString:@"5s"]) {
        [self startTimer];
    }
    if (self.position==JMPublicAlertViewPositionBottom) {
        self.closeBtn.bottom = self.top-10;
        self.closeBtn.right = self.width-10;
    }
    
    self.firstBtn.enabled = YES;
    self.secondBtn.enabled = YES;
    [JF_KEY_WINDOW() addSubview:self.coverBtn];
}
-(void)dismiss{
    
    [self.secondBtn endLoading];
    [self.firstBtn endLoading];
    [self stopTimer];
    delayOperation(0.01, ^{
        [self removeFromSuperview];
        [self.coverBtn removeFromSuperview];
    });
    delayOperation(0.1, ^{
        [[NSNotificationCenter defaultCenter]postNotificationName:@"AlertDismiss" object:nil];
    });
}
-(void)dealloc{
    NSLog(@"alertView Dismiss");
}
@end
